package com.leen.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局配置(spring-mvc的前端控制器 DispatcherServlet)
 * @author wy
 */
@Configuration
public class MvcConfig  extends WebMvcConfigurationSupport {

    /**
     * 配置消息转换  json
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //中文乱码的问题
        List<MediaType> types = new ArrayList<MediaType>();
        types.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(types);
        fastConverter.setDefaultCharset(Charset.forName("UTF-8"));

        converters.add(fastConverter);

        //5、追加默认转换器
        super.addDefaultHttpMessageConverters(converters);
    }


    /**
     * 静态资源放行
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");

        /*放行swagger*/
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");


        super.addResourceHandlers(registry);
    }

    /**
     * 跨域配置
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                // 本个项目提供的所有的url地址都可以放行
                .addMapping("/**")
                .allowedOrigins("*")
                //公共访问的请求方式
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                //访问站网是否允许携带其它数据( cookie)
                .allowCredentials(true)
                //两次请求缓存时间(1分钟)
                .maxAge(3600);
    }



}
